import sys
import time

import clr

import logger

# 添加INCA-COM组件引用
sys.path.append(r'C:\ETAS\INCA7.1\cebra')  # 按实际路径修改
clr.AddReference('incacom')
clr.AddReference('Etas.Base.ComSupport')

# 导入API命名空间
from de.etas.cebra.toolAPI import Inca


class IncaController:
    def __init__(self):
        """初始化INCA连接"""
        self.logger = logger.DataLogger()
        try:
            self.inca = Inca.Inca()  # 创建INCA实例
            # print("INCA版本:", self.inca.APIVersion())   # 获取当前软件版本
            self.experiment = self.inca.GetOpenedExperiment()  # 获取当前实验
            # print(self.experiment)
        except Exception as e:
            print(f"INCA连接失败: {str(e)}")
            sys.exit(1)

    def read_measurement(self, var_name):
        # 读取测量变量值
        measure = None
        try:
            measure = self.experiment.GetMeasureElement(var_name)
            measure1 = measure.GetValue()
            return measure1.GetDoublePhysValue()
        except Exception as e:
            print(f"读取测量变量{var_name}失败: {str(e)}")
            return None
        finally:
            if measure is not None:
                del measure

    def write_calibration(self, cal_name, new_value, time_value):
        """
        写入标定参数
        该方法用于更新实验中的一个标定参数，并记录该操作的日志如果更新失败，会捕获异常并记录错误日志
        参数:
        cal_name (str): 标定参数的名称
        new_value (float): 标定参数的新值
        time_value (float): 标定参数稳定所需的时间
        """
        # 确保标定参数写入前，程序已经启动一段时间，以确保系统稳定
        time.sleep(0.2)
        try:
            # 获取指定名称的标定元素
            cal = self.experiment.GetCalibrationElement(cal_name)
            # 获取当前标定参数的值
            cal1 = cal.GetValue()
            # print(cal1)
            # 设置新的标定参数值，并获取设置后的状态
            cal2 = cal1.SetDoublePhysValue(new_value)
            # 记录操作时间
            inca_time = time.strftime("%Y-%m-%d  %H:%M:%S")
            print(f"{inca_time}-标定参数{cal_name}已更新为{new_value}稳定时间为：{time_value}s,{cal2}")
            # 记录成功的标定操作日志
            self.logger.log_operation('CALIBRATION', cal_name, new_value, time_value, 'SUCCESS')
        except Exception as e:
            # 打印标定参数更新失败的错误信息
            print(f"写入标定参数{cal_name}失败: {str(e)}")
            # 记录失败的标定操作日志
            self.logger.log_operation('CALIBRATION', cal_name, new_value, time_value, 'FAILED')

    # def write_calibrations_batch(self, cal_list):
    #     """批量写入标定参数   功能还未完善"""
    #     for cal_name, new_value, time_value in cal_list:
    #         self.write_calibration(cal_name, new_value, time_value)

    def __del__(self):
        """释放INCA资源"""
        if hasattr(self, 'inca'):
            del self.inca


if __name__ == "__main__":
    # 调用 IncaController类
    controller = IncaController()

    # 测量值变量名  和 调用读取测量值函数
    # Measurename = 'Oil_pSwmp'
    # MeasureValue = controller.read_measurement(Measurename)
    # print(MeasureValue)

    setcalname = "UDC_swtSetP_C"
    setcalValue = 3
    controller.write_calibration(setcalname, setcalValue, 3)

    # 批量标定调用   功能还未完善
    # cal_list = [
    #     ("UDC_swtSetP_C", 3, 1),
    #     ("AnotherCalParam", 5, 2)
    # ]
    # controller.write_calibrations_batch(cal_list)
